<template>
  <div class="banners-container">
    <div class="header">
      <h2>Banner管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        添加Banner
      </el-button>
    </div>

    <!-- 筛选条件 -->
    <div class="filters">
      <el-form :model="filters" :inline="true">
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="激活" value="ACTIVE" />
            <el-option label="禁用" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBanners">搜索</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- Banner列表 -->
    <el-table :data="banners" v-loading="loading" stripe>
      <el-table-column type="index" label="#" width="50" />
      <el-table-column label="预览" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.imageUrl"
            :preview-src-list="[row.imageUrl]"
            style="width: 60px; height: 40px;"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="150" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="linkUrl" label="链接地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="sortOrder" label="排序" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'ACTIVE' ? 'success' : 'danger'">
            {{ row.status === 'ACTIVE' ? '激活' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="editBanner(row)">编辑</el-button>
          <el-button 
            size="small" 
            :type="row.status === 'ACTIVE' ? 'warning' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.status === 'ACTIVE' ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteBanner(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadBanners"
        @current-change="loadBanners"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入Banner标题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            rows="3"
            placeholder="请输入Banner描述"
          />
        </el-form-item>
        <el-form-item label="图片地址" prop="imageUrl">
          <el-input v-model="form.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入跳转链接（可选）" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="ACTIVE">激活</el-radio>
            <el-radio label="INACTIVE">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBanner" :loading="saving">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const banners = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  status: ''
})

// 表单数据
const form = reactive({
  id: null,
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  sortOrder: 0,
  status: 'ACTIVE'
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入Banner标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2到100个字符', trigger: 'blur' }
  ],
  imageUrl: [
    { required: true, message: '请输入图片地址', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑Banner' : '添加Banner')

// 方法
const loadBanners = async () => {
  loading.value = true
  try {
    // 这里应该调用实际的API
    // const response = await bannerApi.getBanners({
    //   page: currentPage.value,
    //   size: pageSize.value,
    //   status: filters.status
    // })
    
    // 模拟数据
    banners.value = [
      {
        id: 1,
        title: '热门美食推荐',
        description: '精选本地热门美食，限时优惠',
        imageUrl: 'https://via.placeholder.com/300x150?text=Banner1',
        linkUrl: '/hot-foods',
        sortOrder: 1,
        status: 'ACTIVE',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        title: '新用户专享',
        description: '新用户注册即享8.8折优惠',
        imageUrl: 'https://via.placeholder.com/300x150?text=Banner2',
        linkUrl: '/new-user',
        sortOrder: 2,
        status: 'ACTIVE',
        createTime: '2024-01-02 10:00:00'
      }
    ]
    total.value = 2
  } catch (error) {
    ElMessage.error('获取Banner列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const editBanner = (banner) => {
  isEdit.value = true
  Object.assign(form, banner)
  dialogVisible.value = true
}

const saveBanner = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate()
  if (!valid) return
  
  saving.value = true
  try {
    if (isEdit.value) {
      // await bannerApi.updateBanner(form.id, form)
      ElMessage.success('更新成功')
    } else {
      // await bannerApi.createBanner(form)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadBanners()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
  } finally {
    saving.value = false
  }
}

const toggleStatus = async (banner) => {
  try {
    const newStatus = banner.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
    // await bannerApi.updateBannerStatus(banner.id, newStatus)
    banner.status = newStatus
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

const deleteBanner = async (banner) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除Banner "${banner.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // await bannerApi.deleteBanner(banner.id)
    ElMessage.success('删除成功')
    loadBanners()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const resetFilters = () => {
  filters.status = ''
  loadBanners()
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    title: '',
    description: '',
    imageUrl: '',
    linkUrl: '',
    sortOrder: 0,
    status: 'ACTIVE'
  })
  formRef.value?.resetFields()
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadBanners()
})
</script>

<style scoped>
.banners-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 